package com.example.myapplication.cutvideo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.text.TextUtils;
import android.util.ArraySet;
import android.view.View;


import com.example.myapplication.shortvideo.utils.DisplayUtils;
import com.example.myapplication.util.SimpleCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: rongfeng
 * @date: 2023/1/6
 * @description
 */
public class JieTu {

    private Context mContext;
    ExecutorService pool;
    Vector<Bitmap> bitmapList;
    private SimpleCallback.Callback mSimpleCallback;

    public JieTu(Context context) {
        this.mContext = context;
        bitmapList = new Vector<>();
        pool = Executors.newFixedThreadPool(5);
    }

    private void saveBitmapDir(String savePath) {
        pool.execute(new Runnable() {
            @Override
            public synchronized void run() {
                if (!bitmapList.isEmpty()) {
                    Bitmap bitmap = bitmapList.remove(0);
                    try {
                        compressAndGenImage(bitmap, savePath);
                        bitmap.recycle();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    if (mSimpleCallback != null) {
                        mSimpleCallback.callback();
                    }
                }
            }
        });
    }

    public void saveEnd(SimpleCallback.Callback callback) {
        mSimpleCallback = callback;
        if (bitmapList.isEmpty()) {
            mSimpleCallback.callback();
        }
    }


    /**
     * view截图
     */
    public void viewShot(final View v, final String filePath) {
        if (null == v) {
            return;
        }
        // 核心代码start
        Bitmap bitmap = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bitmap);
        v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
        v.draw(c);
        // end
        String savePath = filePath;
        if (TextUtils.isEmpty(savePath)) {
            savePath = createImagePath();
        }
        try {
            compressAndGenImage(bitmap, savePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public String createImagePath() {
        //判断sd卡是否存在

        //文件名
        long systemTime = System.currentTimeMillis();
        String path = mContext.getCacheDir().getAbsolutePath();

        File dirFile = new File(path + "/temp");
        if (!dirFile.isDirectory()) {
            dirFile.mkdir();
        }
        String filePath = path + "/temp/" + systemTime + ".png";
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filePath;
    }

    public Bitmap imageScale(Bitmap bitmap, int dst_w, int dst_h) {
        int src_w = bitmap.getWidth();
        int src_h = bitmap.getHeight();
        if (src_w > dst_w) {
            float scale_w = ((float) dst_w) / src_w;
            float scale_h = ((float) dst_h) / src_h;
            Matrix matrix = new Matrix();
            matrix.postScale(scale_w, scale_h);
            Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix,
                    true);
            return dstbmp;
        }
        return bitmap;
    }

    public String capture(View... views) {
        int bgWidth = DisplayUtils.getWidthPixels();
        int bgHeight = (int) (bgWidth * (16f / 9f));

//        int bgWidth = 720;
//        int bgHeight = 1280;

        Bitmap newmap = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);

//        Bitmap bitmap1 = imageScale(BitmapFactory.decodeResource(getResources(), R.mipmap.share_bk), bgWidth, bgHeight);
//        canvas.drawBitmap(bitmap1, 0, 0, null);

        for (View view : views) {
            //使控件可以进行缓存

            view.setDrawingCacheEnabled(true);
            long time1 = System.currentTimeMillis();
            //获取缓存的 Bitmap
            Bitmap drawingCache = view.getDrawingCache();
            //复制获取的 Bitmap
            System.out.println("ssss time 1" + (System.currentTimeMillis() - time1));
            drawingCache = Bitmap.createBitmap(drawingCache);

            //关闭视图的缓存
            view.setDrawingCacheEnabled(false);

            canvas.drawBitmap(drawingCache, 0, 0, null);

        }



        canvas.save();

        canvas.restore();

        bitmapList.add(newmap);
        String savePath = createImagePath();
        saveBitmapDir(savePath);

        return savePath;
    }

    public static void compressAndGenImage(Bitmap image, String outPath) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // scale
        int options = 70;
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, options, os);

        // Generate compressed image file
        FileOutputStream fos = new FileOutputStream(outPath);
        fos.write(os.toByteArray());
        fos.flush();
        fos.close();
//        System.out.println("ssss " + outPath);
    }

    public void deleteTempFile() {
        String path = mContext.getCacheDir().getAbsolutePath();
        File file = new File(path + "/temp");
        if (!file.exists()) {//判断文件是否存在
            return;
        } else {
            File files[] = file.listFiles();
            for (File newfile : files) {//遍历文件夹下的目录
                if (newfile.isFile()) {//如果是文件而不是文件夹==>可直接删除
                    newfile.delete();
                }
            }
            file.delete();
        }
    }


}
